import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addAction } from '../store/action/todo';

export default function Header() {
  // ✨不需要把所有的数据都放在 redux 中
  // 需求1：受控组件改造
  const [name, setName] = useState('');

  const dispatch = useDispatch();
  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      if (name) {
        dispatch(addAction(name));
        setName('');
      } else {
        alert('输入内容为空~');
      }
    }
  };

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
        //  1.1 state控制value或者checked
        //  1.2 onChange配合setState修改state
        value={name}
        onChange={(e) => setName(e.target.value)}
        onKeyDown={handleKeyDown}
      />
    </header>
  );
}
